package org.chameleon.lang.util;

import org.aspectj.lang.ProceedingJoinPoint;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;


public class FallBackUtil {


    public static final String NULL_FALLBACK_METHOD = "nullFallbackMethod";
    public static final String EMPTY_FALLBACK_METHOD = "emptyFallbackMethod";
    public static final String DEFAULT_FALLBACK_METHOD = "defaultFallbackMethod";

    public static Object invokeFallbackMethod(ProceedingJoinPoint joinPoint, String fallback) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = MethodUtil.findFallbackMethod(joinPoint, fallback);

        final Class<?> returnType = method.getReturnType();
        if (DEFAULT_FALLBACK_METHOD.equals(fallback)){

            if (returnType.isAssignableFrom(Collection.class)){
                return Collections.EMPTY_LIST;
            }
            if (returnType.isAssignableFrom(Object.class)){
               return null;
            }
        }
        if (NULL_FALLBACK_METHOD.equals(fallback)) {
            return null;
        }
        if (EMPTY_FALLBACK_METHOD.equals(fallback)) {
            return Collections.EMPTY_LIST;
        }
        method.setAccessible(true);
        return method.invoke(joinPoint.getTarget(), joinPoint.getArgs());
    }
}
